package cn.bob.exception;

import cn.bob.result.JsonResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author bob
 * @data 2022/11/17-9:59
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public JsonResult exceptionHandler(Exception e){
        e.printStackTrace();
        return JsonResult.error(e);
    }

    @ExceptionHandler(GlobalException.class)
    public JsonResult globalExceptionHandler(GlobalException globalException){
        globalException.printStackTrace();
        return JsonResult.error(globalException);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        StringBuilder sb=new StringBuilder();
        //获取校验参数的注解 message的数据
        e.getBindingResult().getAllErrors().forEach(error->{
            sb.append(error.getDefaultMessage()).append("--");
        });
        return JsonResult.error(sb.toString(),GlobalExceptionEnum.COMMON_PARAM_JSR303_ERROR.getExceptionCode());
    }

}
